package com.innjia.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.innjia.sys.entity.UserEntity;
import com.innjia.sys.service.OAuth2LoginService;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 雄安APP Oauth2登录
 * <br>
 * 2017-11-21
 *
 * @author zhouxianglh@gmail.com
 */
@Service("oAuth2LoginServiceXiongAn")
public class OAuth2LoginServiceXiongAnImpl implements OAuth2LoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OAuth2LoginServiceXiongAnImpl.class);

    private static final String URL_TOKEN = "accessToken";

    private static final String URL_USER = "userInfo";

    @Value("${login.xiongan.host}")
    private String host;

    @Value("${login.xiongan.clientId}")
    private String clientId;

    @Value("${login.xiongan.clientSecret}")
    private String clientSecret;


    @Override
    public Map<String, String> getAccessToken(Map<String, String> requestParams) {
        String url = host + URL_TOKEN;
        Map<String, Object> params = new TreeMap<>();
        params.put("clientId", clientId);
        params.put("code", requestParams.get(OAuth2LoginService.KEY_AUTH_CODE));
        params.put("uid", requestParams.get(OAuth2LoginService.KEN_UID));
        params.put("timestamp", System.currentTimeMillis());
        params.put("clientSecret", clientSecret);
        params.put("sign", SecureUtil.md5(params.toString()));
        String result = HttpUtil.post(url, params);
        LOGGER.error(result);
        JSONObject json = JSONObject.parseObject(result);
        Map<String, String> value = new HashMap<>(2);
        value.put(OAuth2LoginService.KEN_TOKEN, json.getString("accessToken"));
        return value;
    }

    @Override
    public UserEntity getUserInfo(Map<String, String> requestParams) {
        String url = host + URL_USER;
        Map<String, Object> params = new TreeMap<>();
        params.put("clientId", clientId);
        params.put("accessToken", requestParams.get(OAuth2LoginService.KEN_TOKEN));
        params.put("timestamp", System.currentTimeMillis());
        params.put("clientSecret", clientSecret);
        params.put("sign", SecureUtil.md5(params.toString()));
        String result = HttpUtil.post(url, params);
        LOGGER.error(result);
        JSONObject json = JSONObject.parseObject(result);
        UserEntity userEntity = new UserEntity();
        userEntity.setPhone(json.getString("phone"));
        return userEntity;
    }
}
